<template>
  <view :class="theme">
    <view class="header bg-21">
      <view class="fd-row ai-center jc-sb" style="margin: 25px 30rpx; height: 25px;">
        <view class="relative fd-row ai-center">
          <view @click="switchOrderTypeTab(typeIndex)" v-for="(item, typeIndex) in orderTypes" :key="typeIndex"
            class="relative mr-60">
            <text :class="[typeIndex === orderTypeIndex ? 'color-2' : 'color-9', `relative fw-700 fs-36`]" :style="{
              textShadow: typeIndex === orderTypeIndex ? `0 0 8rpx rgba(86, 189, 252, 0.6)` : `unset`,
              zIndex: 1,
              transition: `all 0.3s ease-in-out`
            }">
              {{ item.text }}
            </text>
          </view>
          <view class="absolute bottom-0 height-8 br-30 bg-23 width-120"
            :style="{ transition: `left 0.3s ease-in-out`, transform: `translateX(-60%)`, left: `calc(100% / ${orderTypes.length} / 2 + 100% / ${orderTypes.length} * ${orderTypeIndex})`, }" />
        </view>
        <navigator url="/pages/client/otc/appeal">
          <text class="fs-28" style="text-decoration: underline;">申诉记录</text>
        </navigator>
      </view>

      <view class="relative fd-row jc-center" style="height: 32px;">
        <view @click="switchOrderStatusTab(statusIndex)" v-for="(option, statusIndex) in orderTypes[orderTypeIndex].data"
          :key="statusIndex" :class="[`color-${statusIndex === orderStatusIndex ? `27` : `6`}`, `fs-28 f1 jc-center`]"
          style="transition: all 0.2s linear;" hover-class="tap-hover" hover-stay-time="100">
          <label class="fs-28 jc-center"
            :style="{ color: statusIndex === orderStatusIndex ? $config.COLOR_2 : $config.COLOR_9 }">
            {{ option.title }}
          </label>
        </view>
        <view class="absolute bottom-0 width-36 height-4 bg-23 br-6"
          :style="{ transition: `left 0.3s ease-in-out`, transform: `translateX(-50%)`, left: `calc(100% / ${orderTypes[orderTypeIndex].data.length} / 2 + 100% / ${orderTypes[orderTypeIndex].data.length} * ${orderStatusIndex})`, }" />
      </view>
    </view>

    <view class="main" style="padding: 20rpx 30rpx;">
      <view v-for="order in orderTypes[orderTypeIndex]?.data[orderStatusIndex]?.list" :key="order.id"
        class="relative bg-21 br-20 oh p-30 mb-20">
        <u-image class="absolute" width="100%" height="100%" src="/static/img/otc/bg-section_2.png" mode="aspectFill" />
        <view class="relative">
          <label v-if="order.expire" class="f1 mb-30 jc-center fw-700">
            <text class="color-9">剩余{{ ["确认支付", "确认收款"][orderTypeIndex] }}时间：</text>
            <u-count-down :color="$config.COLOR_10" separatorColor="#999" bg-color="transparent" :showBorder="false"
              :showDays="false" :timestamp="order.expire" fontSize="30" />
          </label>
          <view @click="viewDetail(order)" class="relative fd-row pb-20">
            <u-image class="absolute top-20 right-0" style="z-index: 1;" width="128" height="128"
              :src="`/static/img/otc/icon-${orderTypes[orderTypeIndex]?.mapStatus[order.status]?.key}.png`" />
            <view class="ai-center">
              <u-image width="104" height="126" src="/static/img/otc/icon-token.png" />
              <text class="mt-12 color-27">星核</text>
            </view>
            <view class="ml-30 f1 jc-sb">
              <view class="lh-40">
                <label>
                  <text class="color-9">订单编号：</text>
                  <text>{{ order.sn || "-" }}</text>
                </label>
                <label>
                  <text class="color-9">交易数量：</text>
                  <text>{{ order.num || 0 }}个</text>
                </label>
                <label>
                  <text class="color-9">交易单价：</text>
                  <text>{{ order.price || 0 }}CNY</text>
                </label>
              </view>
              <label>
                <text class="color-9">交易时间：</text>
                <text>{{ order.created_time || "-" }}</text>
              </label>
            </view>
          </view>
          <view class="mt-20">
            <label class="ai-baseline jc-end">
              <text class="color-9">总价：</text>
              <text class="fs-40 color-27 fw-700">{{ ((order.price * order.num) || 0).toFixed(2) }}</text>
              <text class="color-27">CNY</text>
            </label>

            <view class="fd-row ai-center jc-end">
              <button v-for="btn in orderTypes[orderTypeIndex]?.mapStatus[order.status]?.operations" :key="btn.key"
                @click="operation(btn.key, order)" hover-class="tap-hover"
                style="margin: 30rpx 0 0 30rpx; border: 2rpx solid #999;"
                :class="[{ dark: `color-9 bg-0`, light: `color-3 bg-23 border-none` }[btn.mode as 'light' | 'dark'], `fs-28 br-50 lh-50`]">
                {{ btn.text }}
              </button>
              <text
                v-if="!orderTypes[orderTypeIndex]?.mapStatus[order.status]?.operations.length && orderTypes[orderTypeIndex]?.mapStatus[order.status]?.text"
                class="mt-30 color-27">
                {{ orderTypes[orderTypeIndex]?.mapStatus[order.status]?.text }}
              </text>
            </view>
          </view>
        </view>

      </view>
      <view class="m-30 ai-center">
        <u-image v-if="!orderTypes[orderTypeIndex].data[orderStatusIndex].list.length" class="mt-60 mb-30" width="360"
          height="360" src="/static/img/blank.png" mode="aspectFit" />
        <u-loadmore :status="orderTypes[orderTypeIndex].data[orderStatusIndex].cache.status" is-dot :load-text="{
          loadmore: '轻轻上拉',
          loading: '努力加载中...',
          nomore: '暂无更多交易订单'
        }" />
      </view>
    </view>
    <u-popup v-model="showPopup.payable" @input="changePopup($event, 'payable')" mode="center" closeable
      :mask-close-able="false" close-icon-color="#fff">
      <view class="br-20 bg-21 p-30 oh" style="width: 600rpx;">
        <label class="fs-28 ai-baseline jc-center mb-12">
          <text style="width: 90rpx; text-align: justify; text-align-last: justify;">需支付</text>
          <text>：</text>
          <text class="fs-40 fw-700 color-27">{{ currentOrder.price * currentOrder.num }}</text>
          <text class="color-27">CNY</text>
        </label>
        <block v-for="(option, key) in payOptions" :key="key">
          <view v-if="currentOrder.pay_type?.includes(option.value) && option.info.account">
            <view @click="copy(option.info.account)" class=" mt-30 fd-row ai-center">
              <u-image width="50" height="50" :src="`/static/img/otc/icon-${key}.png`" />
              <text class="f1 ml-20 fs-28 color-9">{{ option.text }}</text>
              <u-image width="30" height="30" src="/static/img/otc/icon-copy.svg" />
            </view>
            <view v-if="option.info.account" class="ml-70 fs-28 color-9">
              <text class="mt-24">{{ option.info.name + " " + option.info.account }}</text>
              <text v-if="option.info.bank || option.info.belong">
                {{ option.info.bank || "-" }} {{ option.info.belong || "-" }}
              </text>
              <u-image @click="showQrCode(option.info.qrCode)" v-if="option.info.qrCode" class="mt-20" radius="10"
                width="50" height="50" src="/static/img/otc/icon-code.png" />
            </view>
          </view>
        </block>
      </view>
    </u-popup>
    <u-popup v-model="showPopup.confirmPaid" @input="changePopup($event, 'confirmPaid')" mode="center" closeable
      :mask-close-able="false" close-icon-color="#fff">
      <view class="br-20 bg-21 p-30" style="width: 600rpx;">

        <label class="fs-36 fw-700 jc-center lh-2 mb-30">确认支付</label>

        <label class="mb-30 fs-28">选择支付方式</label>
        <radio-group @change="changePayOption">
          <block v-for="(option, key) in payOptions" :key="key">
            <label v-if="currentOrder.pay_type?.includes(option.value) && option.info.account"
              class="mb-30 fd-row ai-center">
              <u-image width="50" height="50" :src="`/static/img/otc/icon-${key}.png`" />
              <text class="f1 ml-20 fs-28 color-9">{{ option.text }}</text>
              <radio :value="String(option.value)" :color="$config.COLOR_10" />
            </label>
          </block>
        </radio-group>

        <label class="mt-50 mb-20 fs-28">上传支付凭证</label>
        <u-image @click="chooseImage" width="200" height="200"
          :src="confirmPaidForm.picture || `/static/img/otc/img-addPicture.png`" />

        <button @click="confirmPaid" class="mt-60 fs-36 fw-700 br-50 color-2 bg-23" hover-class="tap-hover"
          style="line-height: 44px; width: 540rpx;">确认支付</button>
      </view>
    </u-popup>
    <u-modal @confirm="confirmReceived" v-model="showPopup.confirmReceived"
      @input="changePopup($event, 'confirmReceived')" :cancel-color="$config.COLOR_9" :confirm-color="$config.COLOR_10"
      title="确认收款" content="是否确定已收款？" />
    <u-modal @confirm="revokeOrder" v-model="showPopup.revoke" @input="changePopup($event, 'revoke')"
      :cancel-color="$config.COLOR_9" :confirm-color="$config.COLOR_10" title="撤销订单" content="是否确定撤销订单？" />
    <u-modal @confirm="appeal" v-model="showPopup.appeal" @input="changePopup($event, 'appeal')"
      :cancel-color="$config.COLOR_9" :confirm-color="$config.COLOR_10" async-close title="冻结交易">
      <label class="mt-30 fs-28 ml-30">请确认是否申请冻结，并说明原因</label>
      <input v-model="appealForm.description" class="mt-30 bg-21 height-88 ml-20 mr-20 br-10 pl-20 pr-20 fs-28"
        placeholder="请输入冻结交易原因" />
      <label class="mt-30 fs-28 ml-30">联系方式</label>
      <input v-model="appealForm.contact" class="mt-30 mb-30 bg-21 height-88 ml-20 mr-20 br-10 pl-20 pr-20 fs-28"
        placeholder="请输入联系方式" />
    </u-modal>
  </view>
</template>

<script lang="ts" setup>

import { useMapState } from "@/common/libs/store";
import { pager, uniNavigator } from "@/common/libs/utils";
import { onLoad, onPullDownRefresh, onReachBottom } from "@dcloudio/uni-app";
import { ref, reactive } from "vue";

const { theme } = useMapState(["theme"]);
const { $config } = getApp().globalData!;

const showPopup = reactive({
  payable: false,
  confirmPaid: false,
  confirmReceived: false,
  appeal: false,
  revoke: false,
});
const payOptions = reactive({
  aliPay: {
    text: "支付宝",
    color: "#1677ff",
    value: 1,
    info: {
      name: "",
      account: "",
      qrCode: ""
    } as AnyObject
  },
  weChat: {
    text: "微信",
    color: "#1aad19",
    value: 2,
    info: {
      name: "",
      account: "",
      qrCode: ""
    } as AnyObject
  },
  bankCard: {
    text: "银行卡",
    color: "#ffb829",
    value: 3,
    info: {
      name: "",
      account: "",
      bank: "",
      belong: ""
    } as AnyObject
  },
  usdt: {
    text: "USDT",
    color: "#27a17c",
    value: 4,
    info: {
      account: "",
    } as AnyObject
  }
});
const mapPayOptionsKey = { 1: "aliPay", 2: "weChat", 3: "bankCard", 4: "usdt" };

const orderTypes = reactive([
  {
    text: "我是买家",
    data: [
      {
        title: "全部",
        page: 0,
        limit: 20,
        list: [] as any[],
        cache: {
          page: 1,
          list: [] as any[],
          status: "nomore"
        },
        status: 0,
        next: false,
      },
      {
        title: "发布中",
        page: 0,
        limit: 20,
        list: [] as any[],
        cache: {
          page: 1,
          list: [] as any[],
          status: "nomore"
        },
        status: 1,
        next: false,
      },
      {
        title: "待支付",
        page: 0,
        limit: 20,
        list: [] as any[],
        cache: {
          page: 1,
          list: [] as any[],
          status: "nomore"
        },
        status: 4,
        next: false,
      },
      {
        title: "待确认",
        page: 0,
        limit: 20,
        list: [] as any[],
        cache: {
          page: 1,
          list: [] as any[],
          status: "nomore"
        },
        status: 6,
        next: false,
      },
      {
        title: "已完成",
        page: 2,
        limit: 20,
        list: [] as any[],
        status: 2,
        cache: {
          page: 1,
          list: [] as any[],
          status: "nomore"
        },
        next: false,
      },
    ],
    mapStatus: {
      1: {
        key: "pending",
        text: "发布中",
        operations: [
          {
            key: "revoke",
            text: "撤销订单",
            mode: "dark"
          },
        ]
      },
      5: {
        key: "canceled",
        text: "",
        operations: []
      },
      4: {
        key: "toBePaid",
        text: "待支付",
        operations: [
          {
            key: "showPayInfo",
            text: "交易信息",
            mode: "light"
          },
          {
            key: "confirmPay",
            text: "确认已支付",
            mode: "dark"
          },
        ]
      },
      6: {
        key: "waitingConfirm",
        text: "等待卖家确认收款...",
        operations: []
      },
      2: {
        key: "completed",
        text: "",
        operations: []
      },
      3: {
        key: "appeal",
        text: "订单申诉中...",
        operations: []
      },
    } as AnyObject
  },
  {
    text: "我是卖家",
    data: [
      {
        title: "全部",
        page: 0,
        limit: 20,
        list: [] as any[],
        cache: {
          page: 1,
          list: [] as any[],
          status: "nomore"
        },
        status: 0,
        next: false,
      },
      {
        title: "待收款",
        page: 0,
        limit: 20,
        list: [] as any[],
        cache: {
          page: 1,
          list: [] as any[],
          status: "nomore"
        },
        status: 4,
        next: false,
      },
      {
        title: "待确认",
        page: 0,
        limit: 20,
        list: [] as any[],
        cache: {
          page: 1,
          list: [] as any[],
          status: "nomore"
        },
        status: 6,
        next: false,
      },
      {
        title: "已完成",
        page: 0,
        limit: 20,
        list: [] as any[],
        cache: {
          page: 1,
          list: [] as any[],
          status: "nomore"
        },
        status: 2,
        next: false,
      },

    ],
    mapStatus: {
      4: {
        key: "toBePaid",
        text: "等待买家支付中...",
        operations: []
      },
      5: {
        key: "canceled",
        text: "",
        operations: []
      },
      6: {
        key: "waitingConfirm",
        text: "待确认",
        operations: [
          {
            key: "viewVoucher",
            text: "付款凭证",
            mode: "dark"
          },
          {
            key: "confirmReceived",
            text: "确认收款",
            mode: "light"
          },
          {
            key: "appeal",
            text: "申诉",
            mode: "dark"
          },
        ]
      },
      2: {
        key: "completed",
        text: "",
        operations: []
      },
      3: {
        key: "appeal",
        text: "订单申诉中...",
        operations: []
      },
    } as AnyObject
  },
]);

const orderTypeIndex = ref(0);
const orderStatusIndex = ref(0);


onLoad(({ type, status }: any) => {
  type && (orderTypeIndex.value = +type);
  status && (orderStatusIndex.value = +status);
  getOrders();
});

onReachBottom(() => getOrders());

onPullDownRefresh(() => {
  initOrders();
  uni.stopPullDownRefresh();
});

const initOrders = () => {
  const orders = orderTypes[orderTypeIndex.value].data[orderStatusIndex.value];

  orders.page = 0;
  orders.limit = 20;
  orders.list = [];
  orders.cache = {
    page: 1,
    list: [],
    status: "nomore"
  };
  orders.next = false;
  getOrders();
}

const switchOrderTypeTab = (index: number) => {
  if (index === orderTypeIndex.value) return;
  if (orderTypes[orderTypeIndex.value].data[orderStatusIndex.value].cache.status === "loading") return;
  orderStatusIndex.value = 0;
  orderTypeIndex.value = index;
  initOrders();
}

const switchOrderStatusTab = (index: number) => {
  if (index === orderStatusIndex.value) return;
  if (orderTypes[orderTypeIndex.value].data[orderStatusIndex.value].cache.status === "loading") return;
  orderStatusIndex.value = index;
  initOrders();
}

const changePopup = (e: boolean, popupKey: keyof typeof showPopup) => {
  showPopup[popupKey] = e;
}

const getOrders = () => {
  const orders = orderTypes[orderTypeIndex.value].data[orderStatusIndex.value];
  pager({ url: ["/buyerList", "/sellerList"][orderTypeIndex.value], data: { status: orders.status } }, orders);
}

const currentOrder = ref<AnyObject>({});
const operation = (key: string, order: AnyObject) => {
  currentOrder.value = order;
  switch (key) {
    case "revoke":
    case "confirmReceived":
    case "appeal":
      showPopup[key] = true;
      break;
    case "viewVoucher":
      viewDetail(order);
      break;
    case "confirmPay":
      confirmPaidForm.picture = "";
      confirmPaidForm.checkPayOption = "";
    case "showPayInfo":
      payOptions.aliPay.info = {
        name: "",
        account: "",
        qrCode: ""
      };
      payOptions.weChat.info = {
        name: "",
        account: "",
        qrCode: ""
      };
      payOptions.bankCard.info = {
        name: "",
        account: "",
        bank: "",
        belong: ""
      };
      payOptions.usdt.info = {
        account: "",
      };
      uni.showToast({ icon: "loading" });
      uni.request({
        url: "/payInfo",
        data: {
          order_id: order.id,
          seller_id: order.seller_id
        },
        success({ data }: any) {
          uni.hideToast();
          data.forEach((item: AnyObject) => {
            const { info }: any = payOptions[<keyof typeof payOptions>mapPayOptionsKey[item.type as keyof typeof mapPayOptionsKey]];
            info.account = item.number || "";
            info.name = item.username || "";
            item.url && (info.qrCode = item.url || "");
            item.bank_address && (info.belong = item.bank_address || "");
            item.bank_name && (info.bank = item.bank_name || "");
          });
          (showPopup as any)[{ showPayInfo: "payable", confirmPay: "confirmPaid" }[key]] = true;
        }
      });
      break;
    default:
      break;
  }
}

const confirmPaidForm = reactive({
  checkPayOption: "",
  picture: ""
});

const changePayOption = ({ detail }: any) => {
  confirmPaidForm.checkPayOption = detail.value;
}

const copy = (text: string) => {
  uni.setClipboardData({
    data: text,
    showToast: true
  });
}

const showQrCode = (url: string) => {
  url && uni.previewImage({ urls: [url] })
}

const confirmPaid = () => {
  if (!confirmPaidForm.checkPayOption) {
    uni.showToast({ title: "请选择支付的方式", icon: "none" });
    return;
  }
  if (!confirmPaidForm.picture) {
    uni.showToast({ title: "请上传支付凭证截图", icon: "none" });
    return;
  }

  function submit(pay_image: string) {
    uni.showToast({ icon: "loading" });
    showPopup.confirmPaid = false;
    uni.request({
      url: "/tradePay",
      data: {
        ex_order_id: currentOrder.value.ex_order_id,
        pay_image,
        pay_type: confirmPaidForm.checkPayOption,
      },
      success() {
        uni.hideToast();
        switchOrderStatusTab(3);
      }
    });
  }

  uni.showToast({ icon: "loading" });
  uni.uploadFile({
    url: $config.API_FILE_UPLOAD,
    filePath: confirmPaidForm.picture,
    formData: { type: "", position: "avatar" },
    name: "file",
    success({ data }: any) {
      uni.hideToast();
      submit(data[0]);
    }
  });
}

const chooseImage = () => {
  uni.chooseImage({
    count: 1,
    sourceType: ["album"],
    sizeType: ["compressed"],
    success({ tempFilePaths }) {
      confirmPaidForm.picture = tempFilePaths[0];
    }
  });
}

const revokeOrder = () => {
  uni.request({
    url: "/revoke",
    data: { order_id: currentOrder.value.id },
    success() {
      showPopup.revoke = false;
      initOrders();
    }
  });
}

const confirmReceived = () => {
  uni.request({
    url: "/tradeConfirm",
    data: { order_id: currentOrder.value.id },
    success() {
      showPopup.confirmReceived = false;
      switchOrderStatusTab(3);
    }
  });
}

const appealForm = reactive({
  contact: "",
  description: ""
})
const appeal = () => {
  if (!appealForm.description) {
    uni.showToast({ title: "请输入申诉原因", icon: "none" });
    return;
  }
  if (!appealForm.contact) {
    uni.showToast({ title: "请输入联系方式", icon: "none" });
    return;
  }

  uni.showToast({ icon: "loading", mask: true });
  uni.request({
    url: "/appeal",
    data: {
      order_id: currentOrder.value.id,
      appeal_remake: appealForm.description,
      appeal_mobile: appealForm.contact,
    },
    success() {
      uni.hideToast();
      showPopup.appeal = false;
      initOrders();
      uni.navigateTo({ url: "/pages/client/otc/appeal" });
    }
  });
}

const viewDetail = (order: AnyObject) => {
  if (!order.ex_order_id) {
    uni.showToast({ title: "暂无此订单信息", icon: "none" });
    return;
  }

  uniNavigator({ url: `/pages/client/otc/orderInfo?order_id=${order[orderTypeIndex.value ? "id" : "ex_order_id"]}` });
}

</script>
<style lang="scss">
page {
  background-color: $uni-bg-color-otc;
  color: $uni-text-color-otc;
}
</style>
<style lang="scss" scoped>
// scss
.header {
  position: fixed;
  left: var(--window-left);
  right: var(--window-right);
  z-index: 10;
}

.main {
  margin-top: 110px;
}
</style>